<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<?php
require_once('php_shared/session_to_db.php');

// Self uid and username
$username = "";
$uid = "";
// Conversation partner's uid and username
$fname = "";
$fuid = "";
// Mysql result array of messages, for later use
$msgs;

session_start();

if( isset($_SESSION['user_id'], $_REQUEST['fuid']) )
{
	if( ($_SESSION['user_id'] == null) || ($_SESSION['user_id'] == '') )
	{
		alert_and_exit("You need to be logged in to join conversations.");
	}else{
		$db_man = new DbUtils();
			
		if( $db_man->connect() )
		{
			$uid = $_SESSION['user_id'];
			$fuid = $_REQUEST['fuid'];
			
			// Check if this is a new conversation or it was validated before
			if( isset($_SESSION["$uid $fuid conv_valid"]) )
			{
				if( $_SESSION["$uid $fuid conv_valid"] != '1' )
				{
					start_conv_session($uid, $fuid, $db_man);
				}
			}else{
				start_conv_session($uid, $fuid, $db_man);
			}
			
			// We should have a valid conversation session by here
			$username = $_SESSION["$uid $fuid conv_source"];
			$fname = $_SESSION["$uid $fuid conv_dest"];
			$conv_start = $_SESSION["$uid $fuid conv_start"];
			
			if( ($_SERVER['REQUEST_METHOD'] == 'GET') && isset($_GET['show_unread']) )
			{
				// Get all messages between these users since (the last unread message ('s msg_time) or the chat session start time)
				// The last -or- part is used to cover for the scenario that, when a user has an unread message
				// and he opens the conv window, that msg will be marked read therefore; **the last unread message ('s msg_time)** will be null
				// and if the user does not post any mesages, window will keep refreshing with the **$_GET['show_unread']** parameter added
				$sql1 = "SELECT * from conversation WHERE ( (from_uid='$fuid' AND to_uid='$uid') OR (from_uid='$uid' AND to_uid='$fuid') ) AND (msg_time>=(SELECT MIN(msg_time) FROM conversation WHERE (from_uid='$fuid' AND to_uid='$uid' AND isread='0') OR msg_time>'$conv_start') ) ORDER BY msg_time ASC";
				$sql2 = "UPDATE conversation SET isread='1' WHERE (from_uid='$fuid' AND to_uid='$uid' AND isread='0')";
			}else{
				if( isset( $_POST['source_uid'], $_POST['dest_uid'], $_POST['usr_msg']) )
				{
					// If user posted any messages, insert them to database
					$sql = "INSERT INTO conversation (from_uid, to_uid, message, msg_time) VALUES('".$_POST["source_uid"]."','".$_POST["dest_uid"]."','".$_POST["usr_msg"]."','".date('Y-m-d H:i:s')."')";
					$db_man->query($sql);
					header("Location: conversation.php?fuid=$fuid");
				}
				
				// Get all messages with msg_time larger than chat session start time
				$sql1 = "SELECT * from conversation WHERE ( (from_uid='$fuid' AND to_uid='$uid') OR (from_uid='$uid' AND to_uid='$fuid') ) AND msg_time>'$conv_start' ORDER BY msg_time ASC";
				$sql2 = "UPDATE conversation SET isread='1' WHERE from_uid='$fuid' AND to_uid='$uid' AND msg_time>'$conv_start'";
			}
			
			$result = $db_man->query($sql1);
			$db_man->query($sql2);
			if( !$result )
			{
				alert_and_exit("An error occured while communicating with database. Please try starting conversation again later.");
			}else{
				$msgs = $result;
			}
			
		}else{
			alert_and_exit("An error occured while communicating with database. Please try starting conversation again later.");
		}
	}
}else{
	alert_and_exit("You need to be logged in to join conversations.");
}

// Start the chat session
function start_conv_session($uid__, $fuid__, $db_man_)
{
	// Confirm that the given uid and fuid are actually exist and are accepted to be friends 
	// and obtain their username during the process
	$uid_ = $db_man_->set_var($uid__);
	$fuid_ = $db_man_->set_var($fuid__);
	$sql = "SELECT r.username, r.id FROM registered_user r, friend f WHERE (f.accepted='1' AND ((f.user_id=$uid_ AND f.friend_id=$fuid_) OR (f.user_id=$fuid_ AND f.friend_id=$uid_))) AND (r.id=f.user_id OR r.id=f.friend_id)";
	$result = $db_man_->query($sql);
	
	if( !$result )
	{
		alert_and_exit("An error occured while communicating with database. Please try starting conversation again later.");
	}elseif( mysql_num_rows($result) == 2 ){
		while( $row = mysql_fetch_assoc($result) )
		{
			if( $row['id'] == $uid_ )
			{
				$from = $row['username'];
			}else{
				$to = $row['username'];
			}
		}
		// Mark conversation session valid
		$_SESSION["$uid_ $fuid_ conv_valid"] = '1';
		$_SESSION["$uid_ $fuid_ conv_source"] = $from;
		$_SESSION["$uid_ $fuid_ conv_dest"] = $to;
		$_SESSION["$uid_ $fuid_ conv_start"] = date('Y-m-d H:i:s');
	}else{
		alert_and_exit("A database inconsistency detected, cannot start conversation.");
	}
}

function alert_and_exit($alert_msg)
{
	print_javascript("alert('$alert_msg');window.close();");;
}

function print_javascript($script)
{
	print "<script type='text/javascript'>$script</script>";
}

?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Conversation | CSE315 IM</title>
    <link href="css/shared.css" rel="stylesheet" type="text/css" />
    <link href="css/speech_bubble.css" rel="stylesheet" type="text/css" />
    <link href="css/conversation.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/speech_bubble.js"></script>
    <script type="text/javascript" src="js/refresh_timer.js"></script>
    <script type="text/javascript" src="js/ie_textContent_fix.js"></script>
</head>

<body onload="auto_refresh(3000);">
	
	<div class="msg_show_area" id="display_area"></div>
    
    <div class="msg_write_area">
        <form action="conversation.php?fuid=<?php print $fuid ?>" method="post">
        	<input type="hidden" name="source_uid" <?php print "value=\"$uid\""; ?>/>
        	<input type="hidden" name="dest_uid" <?php print "value=\"$fuid\""; ?>/>
            <input class="msg_input" type="text" name="usr_msg" id="usr_msg_input" onfocus="JavaScript:stop_refresh();auto_refresh(15000);" />
            <input class="send_msg_button" type="submit" value="Send" name="send_msg_button" />
        </form>
    </div>
	
    <div class="conv" style="display:none;" id="conv_template">
        <div class="conv_title_top"><b class="b1h"></b><b class="b2h"></b><b class="b3h"></b><b class="b4h"></b></div>
        <div class="conv_header"></div><!-- end #conv_header -->
        <div class="conv_title_bottom"><b class="b1h"></b><b class="b2h"></b><b class="b3h"></b><b class="b4h"></b></div>
        <div class="prompt_content conv_content"></div><!-- end #conv_content -->
        <b class="b4bh"></b><b class="b3bh"></b><b class="b2bh"></b><b class="b1h"></b>
    </div><!-- end #conv -->
    
    <?php
		// Append all message bubbles to the message show area
		if( isset($msgs) )
		{
			while( $row = mysql_fetch_assoc($msgs) )
			{
				if( $uid == $row['to_uid'] )
				{
					$incoming = "true";
					$source = $fname;
					
				}else{
					$incoming = "false";
					$source = $username;
				}
				print_javascript("create_conv_bubble('$source','".$row['message']."', '".$row['msg_time']."', $incoming);");
			}
		}
	?>
</body>
</html>